# 导入:
import sqlalchemy
from sqlalchemy import Column, String, Integer, DateTime, delete
from utils.sql.db import session, Base
from utils.sql.app.user import User
import time
from utils.sql.public.location import phone_location


# 定义User对象:
class Ganger(Base):
    # 表的名字:
    __tablename__ = 'ganger'

    # 表的结构:
    id = Column(Integer(), primary_key=True, default=None)
    user_id = Column(String(60))
    ganger_name = Column(String(20))
    ganger_phone = Column(String(20))
    native_place = Column(String(20), default='')
    ganger_default = Column(String(20), default='0')
    create_time = Column(String(20), default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# 获取工头列表
# 用于分页查询--每页数量
size = 15


def get_ganger_list(user_id: str, query='', current=1):
    ganger = None
    try:
        # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
        lists = session.query(Ganger).order_by(Ganger.id.desc()).filter(Ganger.user_id == user_id)
        if lists:
            start = (current - 1) * size
            end = current * size
            if query:
                lists = lists.filter(Ganger.ganger_name.like(f'%{query}%'))
            ganger = lists.slice(start, end).all()
            return {
                "code": 200,
                "data": ganger,
                "message": '查询成功'
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": "",
            "message": '查询失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 获取单个工头信息
def get_ganger(gangerid: str, userid: str):
    ganger = None
    try:
        # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
        ganger = session.query(Ganger).filter(Ganger.user_id == userid, Ganger.id == gangerid).one()
        if ganger:
            return {
                "code": 200,
                "data": ganger,
                "message": '查询成功'
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": "",
            "message": '查询失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 添加工头
def insert_ganger(data, user_id):
    try:
        location = ''
        location = phone_location(data.ganger_phone)
        # 创建新Ganger对象:
        new_ganger = Ganger(
            user_id=user_id,
            ganger_name=data.ganger_name,
            ganger_phone=data.ganger_phone,
            native_place=location,
            create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        )
        # 添加到session:
        session.add(new_ganger)
        # 提交即保存到数据库:
        session.commit()
        return {
            "code": 200,
            "data": "",
            "message": "数据添加成功"
        }
    except sqlalchemy.exc.IntegrityError as e:
        return {
            "code": 201,
            "data": e,
            "message": "数据已经存在"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 删除工头
def delede_ganger(id, dedaults, user_id):
    try:
        # 创建一个delete对象
        # delete_query = delete(Ganger).where(Ganger.id == id)
        delete_query = session.query(Ganger).filter(Ganger.id == id, Ganger.user_id == user_id)
        # 执行删除操作
        delete_query.delete()
        if dedaults == '1':
            # # 更新用户工头id
            user = session.query(User).filter(User.user_id == user_id).one()  # 添加合适的过滤条件
            user.ganger_id = ''
        # 提交即保存到数据库:
        session.commit()
        # print(is_exist)
        return {
            "code": 200,
            "data": '',
            "message": "操作成功"
        }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": e,
            "message": "数据查询失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 更新工头信息
def update_info(data, user_id):
    # 查询要更新的记录
    try:
        query = session.query(Ganger).filter(Ganger.id == data.id, Ganger.user_id == user_id)  # 添加合适的过滤条件
        result = query.all()
        for item in result:
            location = ''
            location = phone_location(data.ganger_phone)
            # 将属性值设置为新的值
            item.ganger_name = data.ganger_name
            item.ganger_phone = data.ganger_phone
            item.native_place = location

        # 提交事务
        session.commit()
        return {
            "code": 200,
            "data": '',
            "message": "操作成功"
        }
    except sqlalchemy.exc.DBAPIError as e:
        return {
            "code": 201,
            "data": e,
            "message": "操作失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 设置工头为当前
def nowaday_ganger(ganger_id, user_id):
    # 查询要更新的记录
    try:
        # 取消其他工头
        try:
            gangers = session.query(Ganger).filter(Ganger.user_id == user_id, Ganger.ganger_default == '1').one()
            gangers.ganger_default = '0'
        except sqlalchemy.exc.NoResultFound as e:
            print('没有设为当前工头的项')
        # # 设置当前工头
        query = session.query(Ganger).filter(Ganger.id == ganger_id, Ganger.user_id == user_id).one()  # 添加合适的过滤条件
        query.ganger_default = '1'
        #
        # # 更新用户工头id
        user = session.query(User).filter(User.user_id == user_id).one()  # 添加合适的过滤条件
        user.ganger_id = ganger_id
        # 提交事务
        session.commit()
        return {
            "code": 200,
            "data": '',
            "message": "操作成功"
        }
    except sqlalchemy.exc.DBAPIError as e:
        return {
            "code": 201,
            "data": e,
            "message": "操作失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()

